package com.zyy.joseata.util;

import com.zyy.joseata.constant.TxConst;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author zhangyy
 */
public class JoSeataContextUtil {

    public static String getTxId(){
        Object txId = getHeaderValue(TxConst.JOSEATA_TXID_HEADER);
        if(txId == null) {
            return null;
        }else{
            return txId.toString();
        }
    }

    private static Object getHeaderValue(String key){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        Object cseContext;
        if (attributes != null) {
            cseContext = ((ServletRequestAttributes) attributes).getRequest().getHeader(key);
            return cseContext;
        }
        return null;
    }

    public static void setAttrTxId(String txId){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            ((ServletRequestAttributes) attributes).getRequest().setAttribute(TxConst.JOSEATA_TXID_HEADER,txId);
        }
    }

    public static String getAttrTxId(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            Object attrValue = ((ServletRequestAttributes) attributes).getRequest().getAttribute(TxConst.JOSEATA_TXID_HEADER);
            if(attrValue != null){
                return attrValue.toString();
            }
        }
        return null;
    }
}
